﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Brunch.Forms
{
	public partial class ProjectConfigForm : BaseEditForm
	{
		public ProjectConfigForm()
		{
			InitializeComponent();
			this.Height -= breadCrumbControl.Height;
		}

		public ProjectConfigForm(string path) : this()
		{
			if (!string.IsNullOrEmpty(path))
			{
				this.ProjectConfig = new ProjectConfig();
				this.ProjectConfig.RootPath = path;

				pnlBreadcrumb.Visible = true;
				
				breadCrumbControl.Path = path;
				breadCrumbControl.BreadcrumbSelected += new EventHandler<EventArgs<string>>(OnBreadcrumbSelected);
				breadCrumbControl.Title = "Select the folder that represents the branch name";
				this.Text = "Configure new project";
				this.Height += breadCrumbControl.Height;
			}
		}

		private ProjectConfig projectConfig;
		public ProjectConfig ProjectConfig
		{
			get { return projectConfig; }
			set
			{
				if (projectConfig != value)
				{
					projectConfig = value;
					this.Text = "Configure project " + projectConfig.ProjectName;
					HookConfig();
				}
			}
		}

		private void HookConfig()
		{
			txtProjectName.DataBindings.Add(
				new Binding("Text", projectConfig, "ProjectName")
				{
					DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
				}
			);
			txtRootPath.DataBindings.Add(
				new Binding("Text", projectConfig, "RootPath")
				{
					DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
				}
			);
		}

		void OnBreadcrumbSelected(object sender, EventArgs<string> e)
		{
			var cfg = BrunchConfig.GetProjectConfig(breadCrumbControl.Path, e.Value);

			txtProjectName.Text = cfg.ProjectName;
			//projectConfig.ProjectName = cfg.ProjectName;

			txtRootPath.Text = cfg.RootPath;
			//projectConfig.RootPath = cfg.RootPath;

			lblBranch.Text = breadCrumbControl.SelectedCrumb;
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			using (var fbd = new FolderBrowserDialog())
			{
				Common.ConfigureBrowseFolderDialog(fbd);

				fbd.SelectedPath = projectConfig.RootPath;
				if (fbd.ShowDialog() == DialogResult.OK)
					projectConfig.RootPath = fbd.SelectedPath;
			}
		}

		protected override bool IsValid()
		{
			return ProjectConfig.IsValid();
		}
	}
}
